package cn.git.bbs.core.service.brand;


import cn.git.bbs.core.bean.product.Brand;
import cn.git.bbs.core.bean.product.BrandQuery;
import cn.git.bbs.core.dao.product.BrandMapper;
import cn.itcast.common.page.Pagination;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.xml.ws.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Service("brandService")
public class BrandServiceImpl implements BrandService{

    @Autowired
    BrandMapper brandMapper;
    public Pagination selectPagination(String name, boolean isDisplay, Integer pageNo) {


        BrandQuery brandQuery = new BrandQuery();
        brandQuery.setPageNo(Pagination.cpn(pageNo));

        brandQuery.setPageSize(10);
        BrandQuery.Criteria criteria = brandQuery.createCriteria();

        StringBuffer str = new StringBuffer();
        if (null != name) {
            criteria.andNameEqualTo(name);
            str.append("name=").append(name);
        }
        criteria.andIsDisplayEqualTo(isDisplay);
        str.append("isDisplay=").append(isDisplay);

       Pagination pagination = new Pagination(brandQuery.getPageNo(),
               brandQuery.getPageSize(),
               brandMapper.countByExample(brandQuery));
       pagination.setList(brandMapper.selectByExample(brandQuery));

        String url = "/brand/list.do";

        pagination.pageView(url,str.toString());

        return pagination;
    }

    public Brand selectBrandById(Long id) {

        Brand brand = brandMapper.selectByPrimaryKey(id);
        return brand;
    }
    @Autowired
    private Jedis jedis;
    public void updateById(Brand brand) {
        jedis.hset("brand",String.valueOf(brand.getId()),String.valueOf(brand.getName()));
        brandMapper.updateByPrimaryKey(brand);
    }

    public List<Brand> selectBrandList() {
        BrandQuery brandQuery = new BrandQuery();
        List<Brand> brands = brandMapper.selectByExample(brandQuery);
        return brands;
    }
    public List<Brand> selectBrandListByRedis() {
        Map<String, String> map = jedis.hgetAll("brand");
        List<Brand> brands = new ArrayList<Brand>();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry:entries){
            Brand brand = new Brand();
            brand.setId(Long.parseLong(entry.getKey()));
            brand.setName(entry.getValue());
            brands.add(brand);
        }
        return brands;
    }
 }
